import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CustomerFlowingWaterService } from './customer-flowing-water.service';
import { DatePipe } from '@angular/common';
import { defalutImg } from 'src/app/comm';
import { NzModalService } from 'ng-zorro-antd/modal';
import { RevenueExpenditureArrs, profitExamineArrs, profitArrivalArrs } from '../status.pipe';
import { CommonService } from 'src/app/services-common/common.service';

@Component({
  selector: 'app-customer-flowing-water',
  templateUrl: './customer-flowing-water.component.html',
  styleUrls: ['./customer-flowing-water.component.scss'],
  providers: [DatePipe]
})
export class CustomerFlowingWaterComponent implements OnInit {
  isCollapse: boolean = false;
  fallback: string = defalutImg;
  seachParams: any = {
    createTime: '', // 开始时间
    endTime: '', // 结束时间
    num: '', // 综合搜索
  };
  dateArrs: any = [];
  siwtchType: number = 1; // 控制开关 1开启 0关闭

  // 收支类型options
  incomeExpenditureOptions: any = [];
  incomeExpendSelected = [];
  // 收益审核状态options
  profitExamineOptions: any = [...profitExamineArrs];
  profitExamineSelected = [];
  // 收益到账状态options
  profitArrivalOptions: any = [...profitArrivalArrs];
  profitArrivalSeleected = [];

  // table
  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // 审核 modal
  isExamineVisible: boolean = false;
  isAdoptLoading: boolean = false; // 通过loading
  isFailLoading: boolean = false; // 不通过loading
  auditDesc: string = ''; // 审核意见

  /**************************************************** 勾选 START **************************************************/
  disabledAll: boolean = false;
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  listOfData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  /**************************************************** 勾选 END ****************************************************/

  // export
  exportLoading = false;

  constructor(
    private message: NzMessageService,
    private services: CustomerFlowingWaterService,
    private commonService: CommonService,
    private datePipe: DatePipe,
    private modal: NzModalService
  ) { }

  async ngOnInit() {
    await this.getIncomeExpenditure();
    this.loadData();
  }

  // 查询账户流水交易类型
  async getIncomeExpenditure() {
    const res: any = await this.commonService.dictListData('account_transaction_type');
    if (res.code == 0) {
      this.incomeExpenditureOptions = res.data.list || [];
    } else {
      this.incomeExpenditureOptions = [];
      this.message.error(res.message);
    }
  }

  /*********************************************** 勾选 Methods START ***********************************************/
  updateCheckedSet(id: number, checked: boolean, item: any): void {
    if (checked && ((item.changeType == 2 && item.auditStatus == 3) || (item.changeType == 1 && item.auditStatus == 0))) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean, item: any): void {
    this.updateCheckedSet(id, checked, item);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value, item));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
    
    /**
     * 提现的待打款、收入的待审核 (注：类型为提现且审核信息为待打款、类型为收入且审核信息为待审核) 可勾选
     * 审核信息 auditStatus：0 待审核 1.审核通过(已打款) 2.审核不通过 3.待打款
     * 类型 changeType：1、收入，2、提现
     */
    this.disabledAll = !this.listOfCurrentPageData.length && !this.listOfCurrentPageData.every(item => (item.changeType == 2 && item.auditStatus == 3) || (item.changeType == 1 && item.changeType == 0));
  }
  /*********************************************** 勾选 Methods END ***********************************************/

  isDisabled(item: any) {
    if ((item.changeType == 2 && item.auditStatus == 3) || (item.changeType == 1 && item.auditStatus == 0)) {
      return false;
    } else {
      return true;
    }
  }

  async loadData() {
    try {
      let paramas = {
        ...this.seachParams,
        transactionType: this.incomeExpendSelected.join(','), // 收支类型
        auditStatus: this.profitExamineSelected.join(','), // 审核状态
        status: this.profitArrivalSeleected.join(','), // 到账状态
        isList: 1, // 是否是直接进入用户流水（1是0否）
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }

      this.tableParams.tableLoading = true;
      const res: any = await this.services.queryWalletRecordTbale(paramas);
      this.tableParams.tableLoading = false;
      if (res.code == 0) {
        const { records, total }: any = res.data.list;
        this.tableData = records;
        this.tableParams.total = total;

        this.siwtchType = res.data.type;
      } else {
        this.message.error(res.message || '数据获取失败')
      }
    } catch (error: any) {
      this.tableParams.tableLoading = false;
      this.siwtchType = 0;
      this.tableData = [];
      this.tableParams.total = 0;
      this.message.error(error)
    }
  }

  // 日期改变
  dateChange(result: any) {
    this.seachParams.createTime = result.length ? this.datePipe.transform(new Date(result[0]), 'yyyy-MM-dd') : '';
    this.seachParams.endTime = result.length ? this.datePipe.transform(new Date(result[1]), 'yyyy-MM-dd') : '';
  }

  // 查询
  queryData() {
    this.tableParams.page = 1;
    this.loadData();
  }
  // 重置
  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }
    this.dateArrs = [];
    this.incomeExpendSelected = []; // 收支类型
    this.profitExamineSelected = []; // 审核状态
    this.profitArrivalSeleected = []; // 到账状态

    this.tableParams.page = 1;
    this.loadData()
  }

  // 批量审核(opne modal)
  batchAudit() {
    if (this.setOfCheckedId.size <= 0) {
      this.message.warning('请先选择所需审核项');
      return
    }
    this.auditDesc = '';
    this.isExamineVisible = true;
  }
  /**
   * 审核: 状态 -- 0 待审核 1.审核通过 2.审核失败
   * @param state 1：通过，2：不通过
   */
  async handleOk(state: number) {
    try {
      let params = {
        auditStatus: state,
        auditDesc: this.auditDesc,
        ids: Array.from(this.setOfCheckedId).join(',')
      }
      if (state == 1) {
        this.isAdoptLoading = true;
      } else {
        this.isFailLoading = true;
      }

      const res: any = await this.services.batchExamineData(params);
      this.isAdoptLoading = false;
      this.isFailLoading = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.setOfCheckedId.clear();
        this.isExamineVisible = false;
        this.loadData();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error: any) {
      this.isAdoptLoading = false;
      this.isFailLoading = false;
      this.message.error(error);
    }
  }
  handleCancel(): void {
    this.isExamineVisible = false;
  }

  // siwtchInterface
  async siwtchInterface() {
    try {
      let params = {
        type: this.siwtchType == 0 ? 1 : 0 // 1：关 0：开
      }
      const res: any = await this.services.examineSwitchData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.loadData();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }
  // 审核开关
  examineSwitch() {
    this.modal.confirm({
      nzClassName: 'service-modal',
      nzTitle: '<i>提示</i>',
      nzContent: `${this.siwtchType == 0 ? '确认关闭自动审核吗？' : '确认开启自动审核吗？'}`,
      nzOnOk: () => {
        this.siwtchInterface();
      }
    });
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadData()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadData()
  }

  // 收支类型文字filter
  typeFilter(type: any) {
    let tempObj: any = this.incomeExpenditureOptions.find((item: any) => {
        return item.content == type;
    })
    return tempObj?.name || '-';
  }

  // 导出
  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let paramas = {
          ...this.seachParams,
          transactionType: this.incomeExpendSelected.join(','), // 收支类型
          auditStatus: this.profitExamineSelected.join(','), // 审核状态
          status: this.profitArrivalSeleected.join(','), // 到账状态
          isList: 1, // 是否是直接进入用户流水（1是0否）
        }
        this.exportLoading = true;
        const res: any = await this.services.exportCustomerWaterData(paramas);
        this.exportLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '用户账户流水');
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }
}
